﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Seven.Entity;
using Seven.EntityBasic;
using Seven.DataModel.ViewModels.DeskModuleAbout;
using Seven.Tools.Extension;

namespace Seven.MsSql.Repositories
{
    public partial class SysUserDeskModuleRepository
    {
        /// <summary>
        /// 根据用户桌面模块ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">用户桌面模块ID</param>
        /// <returns></returns>
        public UserDeskModuleModel GetEditModelByID(int id)
        {
            var deskModule = new SysDeskModuleRepository(this.dbContext).Entities();
            var data = (from a in this.Entities().Where(w => w.ID == id)
                        join b in deskModule on a.DeskModuleID equals b.ID
                        select new
                        {
                            a.ID,
                            a.DeskModuleID,
                            DeskModuleName = b.Name,
                            a.Location,
                            a.SortNumber,
                            b.ControlType,
                            a.Size,
                            a.Height,
                            a.ReceiveMessage,
                            a.IsShow
                        }).FirstOrDefault();

            return data.CastTo<UserDeskModuleModel>();
        }

        /// <summary>
        /// 根据用户ID获取该用户的桌面模块集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="ignoreDisabled">是否忽略禁用的桌面模块</param>
        /// <returns></returns>
        public IEnumerable<SysDeskModule> GetDeskModules(int userId, bool ignoreDisabled = false)
        {
            var userDeskModule = this.Entities().Where(w => w.UserID == userId);
            if (!ignoreDisabled) { userDeskModule = userDeskModule.Where(w => !w.IsDisabled); }
            var deskModule = new SysDeskModuleRepository(this.dbContext).Entities();

            var query = (from a in userDeskModule
                         join b in deskModule on a.DeskModuleID equals b.ID
                         select b).OrderBy(o => o.SortNumber);

            return query.ToArray();
        }

        /// <summary>
        /// 根据用户ID获取该用户有权限的桌面模块的ID集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public IEnumerable<int> GetDeskModuleIDs(int userId)
        {
            return this.Entities().Where(w => w.UserID == userId && !w.IsDisabled).Select(s => s.DeskModuleID).ToArray();
        }

        /// <summary>
        /// 根据用户ID获取用户有权限的桌面模块数据模型集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="location">位置</param>
        /// <param name="includeNotShow">是否包含“不显示的桌面模块”</param>
        /// <returns></returns>
        public IEnumerable<UserDeskModuleModel> GetUserDeskModuleModels(int userId, DeskModuleLocation? location = null, bool includeNotShow = false)
        {
            var userDeskModule = this.Entities().Where(w => w.UserID == userId && !w.IsDisabled);
            if (location.HasValue) { userDeskModule = userDeskModule.Where(w => w.Location == location.Value); }
            if (!includeNotShow) { userDeskModule = userDeskModule.Where(w => w.IsShow); }
            var deskModule = new SysDeskModuleRepository(this.dbContext).Entities();

            var query = (from a in userDeskModule
                         join b in deskModule on a.DeskModuleID equals b.ID
                         select new
                         {
                             a.ID,
                             a.DeskModuleID,
                             DeskModuleName = b.Name,
                             a.Location,
                             a.SortNumber,
                             b.ControlType,
                             a.Height,
                             a.Size,
                             a.ReceiveMessage,
                             a.IsShow,
                             b.MenuID,
                             Url = b.ActionName
                         }).OrderBy(o => o.Location).ThenBy(o => o.SortNumber).ToArray();

            return query.Select(s => s.CastTo<UserDeskModuleModel>());
        }

        /// <summary>
        /// 根据用户ID获取用户桌面模块集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="includeDisabled">是否包含禁用的桌面模块</param>
        /// <returns></returns>
        public IEnumerable<SysUserDeskModule> GetUserDeskModules(int userId, bool includeDisabled = false)
        {
            return includeDisabled ? this.Get(g => g.UserID == userId) : this.Get(g => g.UserID == userId && !g.IsDisabled);
        }

        /// <summary>
        /// 向所有用户添加指定桌面模块的权限
        /// </summary>
        /// <param name="deskModuleId">桌面模块ID</param>
        /// <returns></returns>
        public int InitUserDeskModule(int deskModuleId)
        {
            string sql = @"declare @DeskModuleID int 
                           declare @Location int 
                           declare @Size int 
                           declare @Height int
                           declare @ReceiveMessage bit 
                           declare @SortNumber int 
                           declare @IsDisabled bit 
                           declare @CreateUserName nvarchar(200)
                           select @DeskModuleID = ID,@Location = Location,@Size = Size,@Height = Height,
                                  @ReceiveMessage = ReceiveMessage,@SortNumber = SortNumber,
                                  @IsDisabled = IsDisabled,@CreateUserName = CreateUserName 
                           from SysDeskModule where ID = @ID
                           insert into SysUserDeskModule (UserID,DeskModuleID,Location,SortNumber,Size,Height,ReceiveMessage,IsShow,IsDisabled,CreateUserName,CreateDate)
                           select ID as UserID,@DeskModuleID,@Location,@SortNumber,@Size,@Height,@ReceiveMessage,cast(1 as bit) as IsShow,@IsDisabled,@CreateUserName,GETDATE() as CreateDate
                           from SysUser";

            return this.ExecSqlCommand(true, sql, new { ID = deskModuleId });
        }

        /// <summary>
        /// 用指定的桌面模块更新所有用户桌面模块中的配置信息，如位置、数据条数、面板高度等
        /// </summary>
        /// <param name="deskModuleId">桌面模块ID</param>
        /// <param name="enforceShow">是否强制显示该桌面模块</param>
        /// <param name="init">是否向新用户初始化该桌面模块</param>
        /// <returns></returns>
        public int ResetUserDeskModule(int deskModuleId, bool enforceShow, bool init)
        {
            StringBuilder sqlBuilder = new StringBuilder("update a");
            sqlBuilder.Append(" set a.Location = b.Location,a.Size = b.Size,a.Height = b.Height,a.ReceiveMessage = b.ReceiveMessage");
            if (enforceShow) { sqlBuilder.Append(" ,a.IsShow = 1"); }
            sqlBuilder.Append(" from SysUserDeskModule a left join SysDeskModule b on a.DeskModuleID = b.ID where b.ID = @ID;");

            int result = this.ExecSqlCommand(sqlBuilder.ToString(), new { ID = deskModuleId });
            if (result > -1 && init)
            {
                string sql = @"declare @Location int 
                           declare @Size int 
                           declare @Height int
                           declare @ReceiveMessage bit 
                           declare @SortNumber int 
                           declare @IsDisabled bit 
                           declare @CreateUserName nvarchar(200)
                           select @Location = Location,@Size = Size,@Height = Height,
                                  @ReceiveMessage = ReceiveMessage,@SortNumber = SortNumber,
                                  @IsDisabled = IsDisabled,@CreateUserName = CreateUserName 
                           from SysDeskModule where ID = @ID
                           insert into SysUserDeskModule (UserID,DeskModuleID,Location,SortNumber,Size,Height,ReceiveMessage,IsShow,IsDisabled,CreateUserName,CreateDate)
                           select ID as UserID,@ID as DeskModuleID,@Location,@SortNumber,@Size,@Height,@ReceiveMessage,cast(1 as bit) as IsShow,@IsDisabled,@CreateUserName,GETDATE() as CreateDate
                           from SysUser
                           where ID not in (select UserID from SysUserDeskModule where DeskModuleID = @ID)";

                result += this.ExecSqlCommand(true, sql, new { ID = deskModuleId });
            }
            return result;
        }

        /// <summary>
        /// 移除指定桌面模块的所有用户桌面模块配置
        /// </summary>
        /// <param name="deskModuleId">桌面模块ID</param>
        /// <returns></returns>
        public int RemoveUserDeskModule(int deskModuleId)
        {
            string sql = " delete SysUserDeskModule where DeskModuleID = @DeskModuleID";

            return this.ExecSqlCommand(sql, new { DeskModuleID = deskModuleId });
        }
    }
}
